#ifndef NET_HPP
#define NET_HPP

#include<iostream>
#include<fstream>
#include<sstream>
#include<stdlib.h>
using namespace std;
#ifdef _WIN32

#include <windows.h>
string fetch_website(const string& url) {
    // 生成临时文件名
    char tmp_path[MAX_PATH];
    if (GetTempPathA(MAX_PATH, tmp_path) == 0) {
        return "[错误] 无法获取临时目录路径";
    }

    char tmp_file[MAX_PATH];
    if (GetTempFileNameA(tmp_path, "web", 0, tmp_file) == 0) {
        return "[错误] 无法创建临时文件";
    }

    // 构建PowerShell命令
    string cmd = "powershell -Command \""
                      "try { "
                      "  $response = Invoke-WebRequest -Uri '" + url + "' -UseBasicParsing -ErrorAction Stop; "
                      "  $response.Content | Out-File -Encoding UTF8 '" + tmp_file + "'; "
                      "  exit 0 "
                      "} catch { "
                      "  Write-Error $_; "
                      "  exit 1 "
                      "}\"";

    // 执行命令并隐藏窗口
    STARTUPINFOA si = { sizeof(si) };
    PROCESS_INFORMATION pi;
    si.dwFlags = STARTF_USESHOWWINDOW;
    si.wShowWindow = SW_HIDE; // 隐藏窗口

    if (!CreateProcessA(NULL, (LPSTR)cmd.c_str(), NULL, NULL, FALSE, 
                       CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) {
        return "[错误] 无法执行PowerShell命令";
    }

    // 等待命令完成
    WaitForSingleObject(pi.hProcess, INFINITE);
    
    // 检查退出代码
    DWORD exit_code;
    GetExitCodeProcess(pi.hProcess, &exit_code);
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);

    if (exit_code != 0) {
        remove(tmp_file);
        return "[错误] 访问网站失败，请检查URL或网络连接";
    }

    // 读取临时文件内容
    ifstream file(tmp_file, ios::binary);
    if (!file.is_open()) {
        remove(tmp_file);
        return "[错误] 无法读取临时文件";
    }

    stringstream buffer;
    buffer << file.rdbuf();
    string content = buffer.str();
    
    // 清理临时文件
    file.close();
    remove(tmp_file);
    
    return content.c_str()+3;
}
#else
#include<unistd.h>
string fetch_website(const string &url){
    char tmp_file[] = "/tmp/web_XXXXXX";
    int fd = mkstemp(tmp_file);
    if (fd == -1) {
        perror("创建临时文件失败");
        return "";
    }
    close(fd);  // 关闭文件描述符，后续通过fstream操作

    // 尝试用curl获取内容
    string cmd = "curl -s \"" + url + "\" > " + tmp_file + " 2>/dev/null";
    int res = system(cmd.c_str());
    
    // 如果curl失败尝试wget
    if (res != 0) {
        cmd = "wget -qO- \"" + url + "\" > " + tmp_file + " 2>/dev/null";
        res = system(cmd.c_str());
        if (res != 0) {
            remove(tmp_file);
            return "[错误] 需要安装curl或wget";
        }
    }

    // 读取临时文件内容
    ifstream file(tmp_file);
    string content((istreambuf_iterator<char>(file)), 
                        istreambuf_iterator<char>());
    
    // 清理临时文件
    remove(tmp_file);
    return content;
}
#endif

#endif